﻿using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using DEMM.Dependency;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.Carto;

namespace DEMM
{
    public partial class MainInterface : Form
    {
        private ArgsData argsData;
        private Point mousePos;

        public MainInterface()
        {
            InitializeComponent();
            this.outputTypeChooser.SelectedIndex = 0;
            this.transMethodChooser.SelectedIndex = 0;

            argsData = new ArgsData();
            mousePos = new Point();
        }

        private void Quit(object sender, EventArgs e)
        {
            this.Close();
        }

        private void TurnWindowMimiSize(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        // 检查TIN路径，若存在则在地图中打开此文件
        private void CheckInputPath(object sender, EventArgs e)
        {
            // 防止在删除已有文本时显示错误提示
            if (this.textBoxInputPath.Text == "") return;

            // 将文本添加进argsData，并检查路径的合法性
            argsData.SetPathInput(this.textBoxInputPath.Text);
            if (argsData.CheckInputPath())
            {
                string folderPath = Directory.GetParent(argsData.GetPathInput()).FullName;

                // 创建并配置一个用于打开TIN数据的工作空间
                IWorkspaceFactory factory = new TinWorkspaceFactoryClass();
                ITinWorkspace workspace = factory.OpenFromFile(folderPath, 0) as ITinWorkspace;
                if (factory.IsWorkspace(folderPath))
                {
                    // 读取TIN数据并将其添加进一个新图层
                    ITin tin_data = workspace.OpenTin(Path.GetFileName(argsData.GetPathInput()));
                    ITinLayer tin_layer = new TinLayerClass
                    {
                        Name = "TIN数据",
                        Dataset = tin_data
                    };

                    // 清除掉原有的图层
                    int limit = this.MapDisplayer.LayerCount;
                    for (int i = 0; i < limit; ++i)
                    {
                        this.MapDisplayer.DeleteLayer(0);
                    }
                    // 添加tin_layer
                    this.MapDisplayer.AddLayer(tin_layer);

                    this.InfoInputPath.Text = "";
                }
                else
                {
                    this.InfoInputPath.Text = "*无法切换至指定TIN文件夹所在的工作空间";
                }
                
            }
            else
            {
                this.InfoInputPath.Text = "*输入路径不正确";
            }
        }

        private void CheckOutputPath(object sender, EventArgs e)
        {
            if (textBoxOutputPath.Text == "") return;

            // 将文本添加进argsData，并检查路径的合法性
            argsData.SetPathOutput(this.textBoxOutputPath.Text);
            if (!argsData.CheckOutputPath())
            {
                this.InfoOutputPath.Text = "*输出路径不正确";
            }
        }

        private void OpenTINInDialog(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                this.textBoxInputPath.Text = folderBrowserDialog.SelectedPath;//选择tin文件夹

            }
        }

        private void OpenDENInDialog(object sender, EventArgs e)
        {
            // 创建并启用一个文件选择窗口
            OpenFileDialog open = new OpenFileDialog
            {
                Title = "输出DEM数据",
                CheckFileExists = false,
                Multiselect = false,
                RestoreDirectory = true,
                Filter = "(*.tif)|*.tif"
            };

            if (open.ShowDialog() == DialogResult.OK)
            {
                this.textBoxOutputPath.Text = open.FileName;
            }
        }

        private void TitleBarArea_MouseDown(object sender, MouseEventArgs e)
        {
            mousePos.X = e.X;
            mousePos.Y = e.Y;
        }

        private void TitleBarArea_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
            this.Location = new Point(this.Location.X + e.X - mousePos.X, this.Location.Y + e.Y - mousePos.Y);
            }
        }

        private void ButtonReset_Click(object sender, EventArgs e)
        {
            // 重置所有的参数
            int limit = this.MapDisplayer.LayerCount;
            for (int i = 0; i < limit; ++i)
            {
                this.MapDisplayer.DeleteLayer(0);
            }
            this.InfoInputPath.Text = "";
            this.InfoOutputPath.Text = "";
            this.InfoTransferData.Text = "";
            this.textBoxInputPath.Text = "";
            this.textBoxOutputPath.Text = "";
            this.outputTypeChooser.SelectedIndex = 0;
            this.transMethodChooser.SelectedIndex = 0;
        }

        private void TransferData(object sender, EventArgs e)
        {
            this.InfoTransferData.Text = "*正在执行转换，请耐心等待……";
            this.Refresh();

            argsData.SetOutType(this.outputTypeChooser.SelectedIndex);
            argsData.SetTransMethod(this.transMethodChooser.SelectedIndex);
            argsData.SetCellSize(Decimal.ToDouble(this.cellSizeInputer.Value));

            if (argsData.Check() != ArgsData.CheckFlags.Perfect)
            {
                this.InfoTransferData.Text = "*参数设置不正确";
                return;
            }

            GeoDataTransfer maker = new GeoDataTransfer();
            if (!maker.TINtoDEM(argsData))
            {
                this.InfoTransferData.Text = "*转换失败，可能是由于传入的TIN数据不正确造成的";
                return;
            }

            string filePath = argsData.GetPathOutput();
            string pathName = System.IO.Path.GetDirectoryName(filePath);
            string fileName = System.IO.Path.GetFileName(filePath);
            IWorkspaceFactory pWSF;
            pWSF = new RasterWorkspaceFactoryClass();
            IWorkspace pWS;
            pWS = pWSF.OpenFromFile(pathName, 0);
            IRasterWorkspace pRWS;
            pRWS = pWS as IRasterWorkspace;
            IRasterDataset pRasterDataset;
            pRasterDataset = pRWS.OpenRasterDataset(fileName);
            IRasterPyramid pRasPyrmid;
            pRasPyrmid = pRasterDataset as IRasterPyramid;

            if (pRasPyrmid != null)
            {
                if (!(pRasPyrmid.Present))
                {
                    pRasPyrmid.Create();
                }
            }
            IRaster pRaster;
            pRaster = pRasterDataset.CreateDefaultRaster();
            IRasterLayer pRasterLayer;
            pRasterLayer = new RasterLayerClass();
            pRasterLayer.CreateFromRaster(pRaster);
            ILayer pLayer = pRasterLayer as ILayer;
            this.MapDisplayer.AddLayer(pLayer, 0);//设置栅格图层的显示层次

            this.InfoTransferData.Text = "";
        }
    }
}
